package com.lance.answer.question_export;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author yixun
 * @version 2.0.0
 * @description 导出题库-2021-06-10 增加填空题
 * 管理英语
 * @date 2021-06-08 18:51
 * @since 2.0.0
 */
public class QuestionExportEng {

    public static void main(String[] args) throws IOException, InterruptedException {

        //课程编码
      //  String subjectCode = "01628";
    //    String subjectCode = "03129";
     //   String subjectCode = "02480";
     //   String subjectCode = "医学免疫学与微生物学";
//        String subjectCode = "管理英语1";
//   //     String majorName = "工商企业管理";
//        String majorName = "行政管理专科";
        String subjectCode = "市场营销原理与实务";
        String majorName = "2022User";
        //并发度，同时开几个浏览器
        int sync = 1;

        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +"-quiz.section");
        List<String> list1 = IOUtils.readLines(inputStream3);
        List<String> paths = new ArrayList<>();
        for (String str:list1) {
            paths.add(str.split(",")[0]);
        }

        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/users/" + majorName +".user");
        List<String> users = IOUtils.readLines(inputStream2,"utf-8");

        List<List<String>> group = new ArrayList<>();

        int size = users.size();
        int step =  size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0;i < sync;i++) {
                List<String> list = users.subList(step * i, (i + 1) * step);
                group.add(list);
            }
            group.add(users.subList(step * sync,users.size()));
        }
        System.out.println(group);

        for (List<String> thread:group) {
            Constant.THREAD_POOL_BATCH.execute(()  -> {
                try {
                    syncGenerateqQuestion(paths,thread,subjectCode);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

        }

    }

    public static void syncGenerateqQuestion(List<String> urlTasks,List<String> users,String subjectCode) throws IOException, InterruptedException {
        for (String user:users) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = "Ouchn"+strs[1].substring(6, 14);
            generateQuestion(urlTasks,subjectCode,userCode,pwd);
        }
    }

    public static void  generateQuestion(List<String> urlTasks,String subjectCode,String userName,String pwd) throws InterruptedException, IOException {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://student.ouchn.cn/";
        driver.get(url);
        Thread.sleep(2000);
        Util.login(driver, userName, pwd);
        Thread.sleep(1000);
        Util.switchToFirst(driver);
        Thread.sleep(2000);
        // 形考作业的链接
        // 形考作业的链接 经济数学基础
        System.err.println("???????????????????");
        Util.clickCourseTaskUrl(driver,subjectCode);
        Thread.sleep(2000);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);
        Util.switchToLast(driver);

        List<Question> questions = Lists.newArrayList();
        for (String urlTask : urlTasks) {
            System.err.println("urlTask:" + urlTask);
            Thread.sleep( 1000);
            driver.get(urlTask);
            Thread.sleep(2 * 1000);;
            // 过滤资源文件下载
            if (urlTask.contains("resource")) {
                continue;
            }
            // 过滤平时行为表现 （如：管理心理学）
            if (urlTask.contains("mod/assign")) {
                continue;
            }
            // box py-3 quizattempt 找到答题区域 点击开始答题
            try {
                WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
            } catch (Exception e) {
                System.err.println("taskUrl:" + urlTask + "  occur error");
                //  e.printStackTrace();
                // FIXME 这里当发现异常时：说明该taskUrl不是做作业的链接url，就需要跳过当前URL。
                continue;
            }

            // 这个url也有一定的信息
            Util.goHomePageIndex(driver);

            // FIXME 当前试卷页面这里可能不在首页（第一页），需要回到首页，按顺序做题
            //  http://xinjiang.ouchn.cn/mod/quiz/attempt.php?attempt=283948&page=2&cmid=166319
            // submitbtns
            Thread.sleep(2000);

            boolean hashNextPage = true;

            while (hashNextPage) {
                try {
                    // 防止太快
                    Thread.sleep(2 * 1000);
                    for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                        if(null == singleSubject){
                            continue;
                        }
                        String answerClass = singleSubject.getAttribute("class");
                        // informationitem  description description
                        if(Strings.isNullOrEmpty(answerClass)){
                            continue;
                        }
                        if(answerClass.contains("description")||answerClass.contains("informationitem")){
                            continue;
                        }
                        Question question = new Question();
                        question.setAnalyze("无");
                        question.setDifficult(1);
                        question.setGradeLevel(21);

                        String questionId = singleSubject.getAttribute("id");
                        // 这里的questionId是题目的ID
                        System.err.println("questionId:" + questionId);
                        WebElement contentElement = singleSubject.findElement(By.className("content"));

                        WebElement hiddenElement = singleSubject.
                                findElement(By.cssSelector("input[type='hidden']"));
                        // 题干
                        String name = hiddenElement.getAttribute("name");
                        System.err.println("name:" + name);
                        // qtext
                        // 题目标题
                        String title = Util.getTitle(contentElement);
                        question.setTitle(title);

                        if (answerClass.contains("multianswer")) {

                            question.setQuestionTypeDesc("完形填空");
                            question.setQuestionType(6);

                            List<WebElement> inputListElement =singleSubject.findElements(By.tagName("input"));
                            System.err.println("inputListElement:" + inputListElement.size());
                            for (WebElement input : inputListElement) {
                                // form-control mb-1
                                if(!input.getAttribute("class").contains("form-control")){
                                    continue;
                                }
                                input.clear();
                            }
                            questions.add(question);
                            continue;
                        }




                        System.err.println("qTitleElement:" + title);
                        // 题目提示 tip prompt
                        WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                        if (null != promptElement) {
                            System.err.println("promptElement:" + promptElement.getText());
                        }

                        // FIXME 填空题没有answer  好像整个填空题都有问题，只能填一个答案，但是有的问题有两个空。
                        // FIXME 填空题没有answer
                        //      WebElement answerElement = contentElement.findElement(By.className("answer"));
                        WebElement answerElement = Util.findByClassName(contentElement, "answer");
                        String labelType = "";
                        List<Item> items = Lists.newArrayList();
                        question.setItems(items);
                        if (null != answerElement) {
                            // 找到每一个选项
                            // 针对多选和单选和判断题
                            for (WebElement singleAnswerElement : answerElement.
                                    findElements(By.cssSelector("div[class='r0'],div[class='r1']"))) {
                                // 答案的序号 判断题没有序号 多选和单选有序号
                                String answerNumber = "";
                                WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                                if (numberElement != null) {
                                    answerNumber = numberElement.getText();
                                }
                                // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                                // fixme 5-28有的答案是纯图片。
                                //     String answerContent = singleAnswerElement.findElement(By.cssSelector("p,label")).getText();
//                                String answerContent = singleAnswerElement.findElement(
//                                        By.cssSelector("div[class='flex-fill ml-1']")).getText();
                                String answerContent = Util.getAnswer(singleAnswerElement);
                                // 找到单选框或复选框
                                WebElement checkboxElement = singleAnswerElement.
                                        findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                                labelType = checkboxElement.getAttribute("type");
                                // 这里的ID是每个选项的ID
                                // answerContent是每个选项的内容
                                String id = checkboxElement.getAttribute("id");
                                System.out.println("id:" + id);
                                System.out.println("answer:" + answerNumber + answerContent);
                                //   System.err.println(id + "\t" + answerNumber + "\t" + answerContent);
                                Item item = new Item();
                                item.setPrefix(answerNumber);
                                item.setContent(answerContent);
                                if (Strings.isNullOrEmpty(answerContent)) {
                                    item.setPrefix(answerContent);
                                }
                                items.add(item);
                            }
                        }

                        answerClass = singleSubject.getAttribute("class");
                        // 简单题que essay manualgraded notyetanswered
                        if (answerClass.contains("essay")) {
                            WebElement iframe = Util.findByTagName(answerElement, "iframe");
                            // 等于选项的ID
                            question.setQuestionType(5);
                            question.setQuestionTypeDesc("简答题");
                            question.setCorrect("简单题");
                            questions.add(question);
                        }
                        // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                        if (answerClass.contains("truefalse")) {
                            question.setQuestionType(3);
                            question.setQuestionTypeDesc("判断题");
                            question.setCorrect("对");
                            questions.add(question);
                        }
                        // 填空题 que shortanswer deferredfeedback notyetanswered
                        if (answerClass.contains("shortanswer")) {
                            WebElement textElement = contentElement.findElement(By.cssSelector("input[type='text']"));
                            String id = textElement.getAttribute("id");
                            // 等于选项的ID
                            question.setQuestionType(4);
                            question.setQuestionTypeDesc("填空题");
                            question.setCorrect("填空题");
                            questions.add(question);
                        }
                        // 多选|单选：que multichoice deferredfeedback notyetanswered
                        if (answerClass.contains("multichoice")) {
                            if ("radio".equals(labelType)) {
                                question.setQuestionType(1);
                                question.setQuestionTypeDesc("单选题");
                                questions.add(question);
                            }
                            if ("checkbox".equals(labelType)) {
                                question.setCorrectArray(new String[]{"A", "B"});
                                question.setQuestionType(2);
                                question.setQuestionTypeDesc("多选题");
                                questions.add(question);
                            }
                        }
                        
                    }

                    // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                    WebElement nextPage = Util.findNextPage(driver);
                    if (nextPage != null) {
                        nextPage.click();
                    } else {
                        hashNextPage = false;
                    }

                } catch (Exception e) {
                    System.err.println("出错啦！！！！" + urlTask);

                    e.printStackTrace();
                    Thread.sleep(2000);
                }

                Thread.sleep(2000);
            }
        }

        // 输出JSON文件；  {id}-题型.json
        Collections.sort(questions);
        List<Map<String,Object>> answers = new ArrayList<>();
        for (Question question:questions) {
            Map<String,Object> answerMap = new HashMap<>();
            answerMap.put("questionType",question.getQuestionType());
            answerMap.put("questionTypeDesc",question.getQuestionTypeDesc());
            answerMap.put("questionTitle",question.getTitle());
            answerMap.put("questionCode", MD5Utils.encode(subjectCode + question.getTitle()));
            answerMap.put("items",question.getItems());
            answerMap.put("answers",Lists.newArrayList("标准答案"));
            // 如果这里是完形填空  就默认为sendKeys
            if(question.getQuestionType()==6){
                answerMap.put("answerType","send");
            }else {
                answerMap.put("answerType","click");
            }
            answers.add(answerMap);
        }
        String rootPath = "src/main/resources/" + subjectCode + "/questions/";
        FileUtils.write(new File(rootPath + userName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat),"utf-8");

        Thread.sleep(5000);
        driver.close();
        driver.quit();
    }
}
